package censorboty;

import java.util.ArrayList;
import java.util.Collections;

import com.google.wave.api.*;

@SuppressWarnings("serial")
public class CensorbotyServlet extends AbstractRobotServlet {
	
	CensorWords cw= new CensorWords();
	@Override
	public void processEvents(RobotMessageBundle bundle) {
		if(bundle.wasSelfAdded()){
			FormElement flm = new FormElement(ElementType.INPUT);
			flm.setValue("Enter Word Here");
			flm.setName("input");
			FormElement btn1 = new FormElement(ElementType.BUTTON);
			btn1.setValue("Add");
			btn1.setName("add");
			FormElement btn2 = new FormElement(ElementType.BUTTON);
			btn2.setValue("Remove");
			btn2.setName("remove");
			TextView tw = bundle.getWavelet().appendBlip().getDocument();
			tw.append("if u want to add a Word\n");
			tw.appendElement(flm);
			tw.append("\n");
			tw.appendElement(btn1);
			tw.append("          ");
			tw.appendElement(btn2);
			tw.append("\n\nThis version doesnt censor older blips...\n");
			tw.append("There are some words in dictionary to censor");
		}
		for(Event e : bundle.getEvents()){
			if(e.getType()==EventType.BLIP_SUBMITTED){
				Blip blip = e.getBlip();
				cencEvent(blip);
			}
			if(e.getType()==EventType.FORM_BUTTON_CLICKED){
				if(e.getButtonName().equals("add")){
					cw.addWord(e);
					editInputBox(e.getBlip().getDocument().getFormView());
				}
				if(e.getButtonName().equals("remove")){
					cw.removeWord(e);
					editInputBox(e.getBlip().getDocument().getFormView());
				}
			}
		}
		
	}
	private void editInputBox(FormView formView){
		FormElement wEdit = formView.getFormElement("input");
		wEdit.setValue("Enter Word Here");
		formView.replace(formView.getFormElement("input"),wEdit);
	}
	private void cencEvent(Blip blip){
		 TextView doc = blip.getDocument();
		 String blipContent = doc.getText().toLowerCase();
		 ArrayList<CensorWordEntry> cwList = new ArrayList<CensorWordEntry>();
		 
		 for(CensorWord cen_word : cw.getCencorWords()){
			 int i=0;
			 while (blipContent.indexOf(cen_word.getWord(), i) != -1){				
					i = blipContent.indexOf(cen_word.getWord(), i);	
					cwList.add(new CensorWordEntry(i, cen_word));		
					i++;										
			} 
		 }
		 
		Collections.sort(cwList);
		Collections.reverse(cwList);
		
		for(CensorWordEntry entry :cwList){
			doc.delete(new Range(entry.getStartpos()+1,(entry.getStartpos()+entry.getCensorW().wordLenght())));
			doc.insert(entry.getStartpos()+1,entry.ret_String());
			}	
	}
}
